package com.zzh.structuredeployment.adapter

import android.animation.Animator
import android.app.Activity
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.zzh.structuredeployment.R
import com.zzh.structuredeployment.auxiliary.ui.ReleaseFooter
import com.zzh.structuredeployment.auxiliary.ui.ReleaseHeader
import com.zzh.structuredeployment.bean.ReleaseBean
import com.zzh.tools.listener.ToolOnClickListener
import com.zzh.tools.system.ToolScreen
import com.zzh.tools.utils.ToolLog

/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2021-01-27
 * @desc
 */

const val HEADER = 0
const val FOOTER = 1
const val ITEM = 2


class ReleaseAdapter(var beans: ArrayList<ReleaseBean>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    interface OnItemClickListener {
        fun onAddClick(position: Int)
        fun onImgClick(position: Int)
        fun onRemove(position: Int)
    }

    open abstract class OnItemDeleteListener {
        var showStatus = -1

        /**
         * 显示删除的状态
         * 0 显示状态
         * -1 隐藏显示
         * 1 删除状态
         */
        fun onDeleteStatus(status: Int, position: Int) {
            if (showStatus == status) return
            showStatus = status
            when (status) {
                -1 -> hideDelete()
                0 -> showDelete()
                1 -> showDeletePrompt()
            }
        }

        protected abstract fun showDelete()

        protected abstract fun showDeletePrompt()

        protected abstract fun hideDelete()

    }


    var context: Context? = null

    private var itemHeight = 0
    private var deleteButtonHeight = 0
    private var mLeftAndRightMargin = 0
    private var mInterval = 0
    var mOnItemClickLesenter: OnItemClickListener? = null
    var mOnItemDeleteListener: OnItemDeleteListener? = null
    var listViewHolder = ArrayList<ViewHolder>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (context == null) {
            context = parent.context
            mLeftAndRightMargin = ToolScreen.dip2px(context, 10f)
            mInterval = ToolScreen.dip2px(context, 5f)
            itemHeight = ((ToolScreen.getScreenWidth(context as Activity)
                .toFloat() - /*mLeftAndRightMargin * 2 -*/ mInterval * 8) / 4).toInt()
            deleteButtonHeight = ToolScreen.dip2px(context, 50f)
        }

        return when (viewType) {
            HEADER -> {
                return ReleaseHeader(context!!, parent)
            }
            FOOTER -> {
                return ReleaseFooter(context!!, parent)
            }
            else -> {
                var viewHolder =
                    ViewHolder(LayoutInflater.from(context).inflate(R.layout.adapter_release, null))
                viewHolder.imgRl?.layoutParams?.height = itemHeight
                viewHolder.imgAdd?.setOnClickListener(mOnToolClickListener)
                viewHolder.img?.setOnClickListener(mOnToolClickListener)
                viewHolder.remove?.setOnClickListener(mOnToolClickListener)
                listViewHolder.add(viewHolder)
                viewHolder
            }
        }


        var viewHolder =
            ViewHolder(LayoutInflater.from(context).inflate(R.layout.adapter_release, null))
        viewHolder.imgRl?.layoutParams?.height = itemHeight
        viewHolder.imgAdd?.setOnClickListener(mOnToolClickListener)
        viewHolder.img?.setOnClickListener(mOnToolClickListener)
//        viewHolder.img?.options?.setDecodeGifImage(false)?.shaper = RoundRectImageShaper(ToolScreen.dip2px(context, 5f).toFloat())
//        viewHolder.img?.options?.shapeSize = ShapeSize(itemHeight, itemHeight, ImageView.ScaleType.CENTER_CROP)
        viewHolder.remove?.setOnClickListener(mOnToolClickListener)
        listViewHolder.add(viewHolder)
        return viewHolder
    }


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        holder.itemView.setTag(R.id.tag_one, position)
        holder.itemView.setTag(R.id.tag_two, 1)
        when (holder) {
            is ViewHolder -> {
                if (holder.itemView.visibility != View.VISIBLE) {
                    holder.itemView.visibility = View.VISIBLE
                }
                var item = beans[position]
                if (!item.isAdd) {
                    Glide.with(context!!).load(item.path).into(holder.img)
                    holder.img.visibility = View.VISIBLE
                    holder.remove.visibility = View.VISIBLE
                    holder.imgAdd.visibility = View.GONE
                    holder.img.setTag(R.id.tag_one, holder)
                    holder.remove.setTag(R.id.tag_one, holder)
                    holder.itemView.setTag(R.id.tag_two, 0)
                } else {
                    holder.img.visibility = View.GONE
                    holder.remove.visibility = View.GONE
                    holder.imgAdd.visibility = View.VISIBLE
                    holder.imgAdd.setTag(R.id.tag_one, holder)
                }
            }
            is ReleaseHeader -> {
            }
            is ReleaseFooter -> {
            }
        }

    }

    override fun getItemCount(): Int {
        return beans?.size
    }

    override fun getItemViewType(position: Int): Int {
        return beans?.get(position).getViewType()
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var imgRl = itemView.findViewById<View>(R.id.imgRl)
        var img = itemView.findViewById<ImageView>(R.id.img)
        var imgAdd = itemView.findViewById<View>(R.id.imgAdd)
        var remove = itemView.findViewById<View>(R.id.remove)
    }

    private var mIsClick = true
    private var mOnToolClickListener = object : ToolOnClickListener() {
        override fun onClick(view: View?) {
            super.onClick(view)
            if (!mIsClick) return
            when (id) {
                R.id.imgAdd -> {
                    var holder = view?.getTag(R.id.tag_one) as ViewHolder
                    if (holder.adapterPosition == -1) return
                    mOnItemClickLesenter?.onAddClick(holder.adapterPosition)
                }
                R.id.img -> {
                    var holder = view?.getTag(R.id.tag_one) as ViewHolder
                    if (holder.adapterPosition == -1) return
                    mOnItemClickLesenter?.onImgClick(holder.adapterPosition)
                }
                R.id.remove -> {
                    var holder = view?.getTag(R.id.tag_one) as ViewHolder
                    if (holder.adapterPosition == -1) return
                    mOnItemClickLesenter?.onRemove(holder.adapterPosition)
                }
            }
        }
    }

    val mItemDecoration = object : RecyclerView.ItemDecoration() {

        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            super.getItemOffsets(outRect, view, parent, state)
            var position = view.getTag(R.id.tag_one) as Int
            if (getItemViewType(position) == ITEM) {
                outRect.left = mInterval
                outRect.right = mInterval
                outRect.top = mInterval
                outRect.bottom = mInterval
            }
        }
    }

    val mItemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {

        var fromPosition = -1
        var toPosition = -1
        var mViewHolder: RecyclerView.ViewHolder? = null
        var mBottomSpacing = Int.MAX_VALUE

        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ): Int {
            if ((viewHolder?.itemView?.getTag(R.id.tag_two) as Int) == 1) {
                return makeMovementFlags(0, 0)
            }
            return makeMovementFlags(
                ItemTouchHelper.UP or ItemTouchHelper.DOWN
                        or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT,
                0
            )
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            if ((target?.itemView?.getTag(R.id.tag_two) as Int) == 1) {
                return false
            }
            viewHolder?.let { holder ->
                target?.let { toHolder ->
                    toPosition = toHolder.adapterPosition
                    notifyItemMoved(holder.adapterPosition, toPosition)
                }
            }
            mViewHolder?.let { holder ->
                calculateBottomSpacing(holder)
            }
            return true
        }

        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
            super.onSelectedChanged(viewHolder, actionState)
            when (actionState) {
                ItemTouchHelper.ACTION_STATE_DRAG -> { // 选中滑动
                    mIsClick = false
                    viewHolder?.let { holder ->
                        fromPosition = holder.adapterPosition
                        toPosition = -1
                        mViewHolder = viewHolder
                        mViewHolder?.let { holder ->
                            holder.itemView.animate().scaleX(1.1f).scaleY(1.1f).setDuration(100)
                                .start()
                            calculateBottomSpacing(holder)
                            updateDeleteStatus(0, holder.adapterPosition)
                        }
                    }
                }
                ItemTouchHelper.ACTION_STATE_IDLE -> { // 滑动结束
                    mViewHolder?.let { holder ->
                        var animatorListener: Animator.AnimatorListener? = mAnimatorListener
                        mOnItemDeleteListener?.let { listener ->
                            if (listener.showStatus == 1) {
                                animatorListener = null
                            }
                        }
                        mBottomSpacing = Int.MAX_VALUE
                        updateDeleteStatus(-1, holder.adapterPosition)
                        animatorListener?.let {
                            holder.itemView.animate().scaleX(1f).scaleY(1f).setDuration(300)
                                .setListener(animatorListener).start()
                            return
                        }
                        holder.itemView.visibility = View.INVISIBLE
                        holder.itemView.animate().scaleX(1f).scaleY(1f).setDuration(0)
                            .setListener(null).start()
                        removeItem(fromPosition)
                        mIsClick = true
                    }
                }
            }
        }

        private fun calculateBottomSpacing(holder: RecyclerView.ViewHolder) {
            var locationScreen = IntArray(2)
            holder.itemView.getLocationOnScreen(locationScreen)
            mBottomSpacing =
                ToolScreen.getScreenHeight(holder.itemView.context as Activity) - locationScreen[1] - itemHeight - deleteButtonHeight
        }

        private fun updateDeleteStatus(status: Int, position: Int) {
            mOnItemDeleteListener?.let {
                it.onDeleteStatus(status, position)
            }
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        }

        override fun onChildDraw(
            c: Canvas,
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            dX: Float,
            dY: Float,
            actionState: Int,
            isCurrentlyActive: Boolean
        ) {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
            when {
                mBottomSpacing == Int.MAX_VALUE -> {
                    updateDeleteStatus(-1, viewHolder.adapterPosition)
                }
                dY > mBottomSpacing -> {
                    updateDeleteStatus(1, viewHolder.adapterPosition)
                }
                else -> {
                    updateDeleteStatus(0, viewHolder.adapterPosition)
                }
            }
        }

        private var mAnimatorListener = object : Animator.AnimatorListener {
            override fun onAnimationCancel(p0: Animator?) {}

            override fun onAnimationEnd(p0: Animator?) {
                mViewHolder?.itemView?.animate()?.setListener(null)
                mIsClick = true
                if (toPosition == -1) return
                if (fromPosition != toPosition) {
                    var fromBean = beans[fromPosition]
                    beans.removeAt(fromPosition)
                    beans.add(toPosition, fromBean)
                }
            }

            override fun onAnimationRepeat(p0: Animator?) {}

            override fun onAnimationStart(p0: Animator?) {}
        }
    })

    /**
     * 删除item
     */
    fun removeItem(vararg positions: Int) {
        positions.forEach { position ->
            beans.removeAt(position)
        }
        if (beans.size > 0) {
            var isAdd = false
            var allowAddStatus = -1
            beans.forEachIndexed { index, releaseBean ->
                if (releaseBean.isAdd) {
                    isAdd = true
                    return@forEachIndexed
                } else if (releaseBean.viewType == FOOTER) {
                    allowAddStatus = index
                    return@forEachIndexed
                }
            }
            if (!isAdd) {
                beans.add(allowAddStatus, createAddPic())
            }
        }
        notifyDataSetChanged()
    }

    private fun createAddPic(): ReleaseBean {
        var bean = ReleaseBean()
        bean.isAdd = true
        bean.viewType = ITEM
        return bean
    }

    /**
     * 获取pic集合
     */
    fun getPicList(): ArrayList<ReleaseBean> {
        var list = arrayListOf<ReleaseBean>()
        beans.forEach {
            if (it.viewType == ITEM && !it.isAdd) {
                list.add(it)
            }
        }
        return list
    }

    /**
     * 获取pic数量
     */
    fun getPicCount(): Int {
        var count = 0
        beans.forEach {
            if (it.viewType == ITEM && !it.isAdd) {
                count++
            }
        }
        return count
    }
}